package com.net.core.utils;


import com.net.core.core.cache.aop.YxCacheable;
import com.net.core.core.cache.aop.YxCacheableHandle;
import com.net.core.core.cache.interfaces.YxCacheHandle;
import com.net.core.models.bean.User;
import com.net.core.core.YXException;
import com.net.core.models.user.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

@Component
public class CurrentCache {

    private static ThreadLocal<String> currentToken = new ThreadLocal<>();

    @Resource
    YxCacheHandle handle;

    static long expireSecond = 60 * 60 * 24;


    public static void setToken(String token, User user) {
        currentToken.set(token);
    }

    public static String getToken() {
        return currentToken.get();
    }

    public void setUser(User user) {
        String token = user.getAccount();
        if (token == null || token.trim().length() == 0) throw new YXException("token 生成有误");
        user.setToken(token);
        handle.put(token, user, expireSecond);//24小时过期
    }

    public User getUser() {
        return getUser(getToken());
    }

    public User getUser(String token) {
        User user;
        Object oUser = handle.get(token);
        if (oUser == null) {
            UserService service = MyUtils.getBean(UserService.class);
            user = service.getUserByAccount(token);
            handle.put(token, user, expireSecond);
        } else {
            user = (User) oUser;
        }
        return user;
    }

    public void putUser(User user) {
        handle.put(user.getToken(), user, expireSecond);
    }
}
